import { useEffect, useState } from 'react';
import {
  Form,
  Table,
  Row,
  Col,
  Input,
  Checkbox,
  Button,
  Pagination,
  Tooltip,
  Switch,
  Divider,
} from 'antd';
import InfiniteScroll from 'react-infinite-scroller';
import styles from './style.less';
import { axconst } from '@/shared/axconst';
import AxModal from '@/components/AxForm/AxModal/index';

const { Search } = Input;
/**
 * 自定义选择表单
 * @param title 表单名称
 * @param visible 可见性
 * @param width 弹窗宽度
 * @param displayField 名称字段（默认：name）
 * @param searchField 名称字段（默认：displayField）
 * @param valueField 值字段（默认：id）
 * @param haveSwitch 是否有开关按钮
 * @param extraColumns 额外的的待选列
 * @param nameWidth 名称列的长度（有默认值，可不指定）
 * @param selectedData 默认选中的数据（默认值[]）
 * @param handleVisible 可见性处理函数
 * @param handleRead 选项数据读取函数
 * @param handleCreate 添加处理函数
 */
const AxSelectForm = props => {
  const {
    loading,
    haveSwitch = false,
    extraColumns = null,
    searchField,
    /** 名称字段 */
    displayField = 'name',
    /** 值字段 */
    valueField = 'id',
    nameWidth,
    width = '40%',
    selectedData: selectedDataFromProps = [],
    handleRead: handleReadFromProps,
    handleCreate: handleCreateFromProps,
    ...rest
  } = props;
  const [data, setData] = useState({
    list: [],
    pagination: {},
  });
  const [selectedData, setSelectedData] = useState(selectedDataFromProps);
  const [checkAll, setCheckAll] = useState(false);
  /** 查询字段 */
  let field = {};
  /** 分页初始值 */
  let page = axconst.page.params;

  /** 初始化数据 */
  useEffect(() => {
    handleRead();
  }, []);

  /** 检查全选状态 */
  const checkAllStatus = d => {
    const fd = d.list.find(i => i.checked === false);
    if (fd) {
      setCheckAll(false);
    } else {
      setCheckAll(true);
    }
  };

  /** 点击行选中 */
  const handleClickRow = (record, flag) => {
    if (record.checked === true) {
      record.checked = false;
    } else {
      record.checked = true;
    }
    setSelectedData(selectedData => {
      if (record.checked === true) {
        selectedData.push(record);
      } else {
        const fd = selectedData.find(v => v[valueField] === record[valueField]);
        selectedData.splice(selectedData.indexOf(fd), 1);
      }
      return selectedData.map(i => i);
    });
    if (!flag) checkAllStatus(data);
  };

  /** 删除选中项 */
  const handleDeselect = record => {
    record.checked = false;
    setSelectedData(selectedData => {
      if (record.checked === true) {
        selectedData.push(record);
      } else {
        selectedData.splice(selectedData.indexOf(record), 1);
      }
      return selectedData.map(i => i);
    });
  };

  /** 切换选中项状态 */
  const handleSwitch = record => {
    setSelectedData(selectedData => {
      selectedData[selectedData.indexOf(record)] = record;
      return selectedData.map(i => i);
    });
  };

  /** 搜索 */
  const handleSearch = val => {
    if (val && val.trim() !== '') {
      if (searchField) {
        field[searchField] = val.trim();
      } else {
        field[displayField] = val.trim();
      }
    } else {
      field = {};
    }
    return handleRead();
  };

  /** 读取数据 */
  const handleRead = () => {
    if (handleReadFromProps)
      return handleReadFromProps(page, field).then((res) => {
        let selectedDataNew = selectedData.map(i => i);
        if (res.list.length > 0) {
          res.list.forEach(c => {
            c.checked = false;
          });
          /** 重新勾选 */
          selectedData.forEach(i => {
            res.list.forEach(c => {
              if (i[valueField] === c[valueField]) {
                c.checked = true;
                selectedDataNew.splice(selectedDataNew.indexOf(i), 1);
                selectedDataNew.push(c);
              }
            });
          });
          checkAllStatus(res);
        }
        setData(res);
        setSelectedData(selectedDataNew);
      });
  };

  /** 保存 */
  const handleCreate = () => {
    if (selectedData && selectedData.length > 0) {
      if (handleCreateFromProps) return handleCreateFromProps(selectedData);
    }
  };

  /** 改变分页 */
  const handlePageChange = (currentPage, pageSize) => {
    page = {
      currentPage,
      pageSize,
    };
    handleRead();
  };

  /** 全选 */
  const handleCheckAll = () => {
    if (data && data.list) {
      data.list.forEach(i => {
        if (checkAll === true) {
          handleClickRow(i, true);
        } else {
          if (i.checked === false) handleClickRow(i, true);
        }
      });
      checkAllStatus(data);
    }
  };

  /** 待选列 */
  const columns = [
    {
      title: '名称',
      dataIndex: displayField,
      width: nameWidth ? nameWidth : extraColumns ? axconst.width.threeonly : null,
      ellipsis: true,
    },
    {
      title: '操作',
      width: axconst.width.two,
      ellipsis: true,
      dataIndex: 'checked',
      render: (text, record) => (
        <Button type="link" size="small">
          <Checkbox checked={text}></Checkbox>
        </Button>
      ),
    },
  ];

  /** 已选列 */
  const selectColumns = [
    {
      title: '名称',
      dataIndex: displayField,
    },
    {
      title: '操作',
      width: 105,
      dataIndex: 'switch',
      render: (text, record) => (
        <span style={{ float: 'right' }}>
          {haveSwitch && (
            <span>
              <Tooltip title={record.switch === true ? '取消管理员' : '设置为管理员'}>
                <Switch
                  size="small"
                  onClick={checked => {
                    record.switch = checked;
                    handleSwitch(record);
                  }}
                />
              </Tooltip>
              <Divider type="vertical" />
            </span>
          )}
          <Button
            type="link"
            style={{ color: 'rgb(218, 218, 218)' }}
            icon="close-circle"
            size="small"
            onClick={() => {
              handleDeselect(record);
            }}
          />
        </span>
      ),
    },
  ];

  /** 额外的的待选列 */
  if (extraColumns && Array.isArray(extraColumns)) {
    extraColumns.reverse().forEach(i => {
      columns.splice(1, 0, i);
    });
  }

  return (
    <AxModal
      {...rest}
      showLoading={false}
      width={width}
      okButtonProps={{ disabled: selectedData.length === 0 }}
      handleCreate={handleCreate}
      items={[
        <Row gutter={12}>
          <Col span={12}>
            <Search
              placeholder="搜索"
              onSearch={val => handleSearch(val)}
              style={{ width: '100%' }}
              allowClear
            />
            <div className={styles.demoInfiniteContainer}>
              <InfiniteScroll
                initialLoad={false}
                pageStart={0}
                loadMore={() => { }}
                // hasMore={!state.loading && state.hasMore}
                useWindow={false}
              >
                <Table
                  rowKey={record => record[valueField]}
                  checkboxModel={false}
                  columns={columns}
                  dataSource={data.list}
                  loading={loading}
                  pagination={false}
                  showHeader={false}
                  onRow={record => ({
                    onClick: () => {
                      handleClickRow(record);
                    },
                  })}
                />
              </InfiniteScroll>
            </div>
            <Pagination
              size="small"
              style={{ float: 'right', marginTop: '5px' }}
              pageSize={page.pageSize}
              total={data && data.pagination && data.pagination.total}
              onChange={handlePageChange}
            />
          </Col>
          <Col span={12}>
            <Button type="link" onClick={handleCheckAll}>
              全选
            </Button>
            <div className={styles.demoInfiniteContainer}>
              <InfiniteScroll
                initialLoad={false}
                pageStart={0}
                useWindow={false}
                loadMore={() => { }}
              >
                <Table
                  rowKey={record => record[valueField]}
                  columns={selectColumns}
                  dataSource={selectedData}
                  pagination={false}
                  showHeader={false}
                />
              </InfiniteScroll>
            </div>
          </Col>
        </Row>,
      ]}
    ></AxModal>
  );
};

export default Form.create()(AxSelectForm);
